package com.daniel.juc.add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 详细说明
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/5/20 17:22
 */
public class SemaphoreDemo {
	public static void main(String[] args) {
		// 线程数量：停车位，限流
		Semaphore semaphore = new Semaphore(3);

		for (int i = 1; i <= 6; i++) {
			new Thread(() -> {
				try {
					// 占用资源
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName() + "抢到车位");
					TimeUnit.SECONDS.sleep(3);
					System.out.println(Thread.currentThread().getName() + "离开车位");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					// 释放资源
					semaphore.release();
				}
			}, String.valueOf(i)).start();
		}
	}
}
